package com.example.util;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.resule.Result;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * @authorDuanyYingZhi
 * @create2022-29-15:30
 */
public class HttpClientUtil {

    public static Object requestGetUrl(String url, Map<String, String> param, String token) throws Exception {

        InputStream is = null;
        String body = null;
        StringBuilder res = new StringBuilder();
        // 设置完整的url
        URIBuilder uriBuilder = null;
        uriBuilder = new URIBuilder(url);
        //添加参数
        for (Map.Entry<String, String> entry : param.entrySet()) {
            uriBuilder.setParameter(entry.getKey(), entry.getValue());
        }
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        httpGet.addHeader("Content-Type", "application/json");
        if (token != null) {
            httpGet.addHeader("token", token);
        }


        RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).build();

        httpGet.setConfig(config);

        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            is = entity.getContent();
            //转换为字节输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(is, Consts.UTF_8));
            while ((body = br.readLine()) != null) {
                res.append(body);
            }
        }


        Object jsonMap = JSON.parse(res.toString());


        return jsonMap;
    }


    public static Object requestPostUrl(String url, Map<String, Object> param, String token) throws Exception {

        InputStream is = null;
        String body = null;
        StringBuilder res = new StringBuilder();
        HttpPost httpPost = new HttpPost(url);

        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
        // httpPost.addHeader("Content-Type", "application/json");
        if (token != null) {
            httpPost.addHeader("token", token);
        }

        // 设置请求的参数
        JSONObject jsonParam = new JSONObject();

        param.forEach((k, v) -> jsonParam.put(k, v));

        StringEntity stringEntity = new StringEntity(jsonParam.toString(), "utf-8");

        stringEntity.setContentEncoding("UTF-8");
        //    stringEntity.setContentType("application/json");
        httpPost.setEntity(stringEntity);

        RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).build();

        httpPost.setConfig(config);

        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            is = entity.getContent();
            //转换为字节输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(is, Consts.UTF_8));
            while ((body = br.readLine()) != null) {
                res.append(body);
            }
        }


        Object jsonMap = JSON.parse(res.toString());


        return jsonMap;
    }

    public static Object formrequestPostUrl(String url, Map<String, Object> param, String token) throws Exception {

        InputStream is = null;
        String body = null;
        StringBuilder res = new StringBuilder();
        HttpPost httpPost = new HttpPost(url);

        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
        // httpPost.addHeader("Content-Type", "application/json");
        if (token != null) {
            httpPost.addHeader("token", token);
        }

        // 设置请求的参数
        JSONObject jsonParam = new JSONObject();

        List<NameValuePair> paramList = new ArrayList<NameValuePair>();
        for (Map.Entry<String, Object> entry : param.entrySet()) {
            paramList.add(new BasicNameValuePair(entry.getKey(), (String) entry.getValue()));
        }


        httpPost.setEntity(new UrlEncodedFormEntity(paramList, "UTF-8"));
        CloseableHttpClient httpClient = HttpClients.createDefault();

//发送请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            org.apache.http.HttpEntity httpEntity = response.getEntity();
//返回状态码200表示请求成功
            if (response.getStatusLine().getStatusCode() == 200) {
                JSONObject resultString = (JSONObject) JSONObject.parse(EntityUtils.toString(response.getEntity(), "UTF-8"));
                return resultString;
            }else {
                return null;
            }


    }
}
